#include "myStdio.h"

FILE_* fopen_(const char* path_name,const char* mode){
  assert(path_name==NULL);
  int flag = 0; //打开文件的方式
  if(strcmp(mode,"r") == 0)
  {
    //读  
    flag |= O_RDONLY;
  }
  else  if(strcmp(mode,"w") == 0)
  {
    flag |= (O_WRONLY | O_CREAT |O_TRUNC);
  }
  else if(strcmp(mode,"a") == 0)
  {
    flag|= (O_WRONLY |O_CREAT |O_APPEND);
  }
  else 
  {
    //do nothing
  }

  int defaultMode = 0666;
  int fd=0;
  if(flag & O_RDONLY) fd = open(path_name,flag);
  else fd = open(path_name,flag,defaultMode);
  if(fd<0)
  {
    const char* err = strerror(errno);
    printf("111111111111");
    write(2,err,strlen(err));
    return NULL;
  }

  FILE_ *fp = (FILE_*)malloc(sizeof(FILE_));
  assert(fp);
  fp->fileno =fd;
  fp->cap = SIZE;
  fp->size=0;
  fp->flush_flag = Line_flush;  //默认为行刷新
  memset(fp->buffer,0,SIZE);
  return fp;
}

void fwrite_(const void* ptr,int num,FILE_* fp)
{
  // 1\写入到缓冲区
  memcpy(fp->buffer+fp->size,ptr,num); //把ptr的内容放到缓冲区
  fp->size+=num;

  // 2、判断是否刷新
  if(fp->flush_flag & Now_flush)
  {
    write(fp->fileno,fp->buffer,fp->size);
    fp->size =0; //将缓冲区的内容清空
  }
  else if(fp->flush_flag & Full_flush)
  {
    if(fp->size == fp->cap)
    {
    write(fp->fileno,fp->buffer,fp->size);
    fp->size  =0;

    }
  }
  else if(fp->flush_flag & Line_flush)
  {
    if(fp->buffer[fp->size-1]=='\n')
    {
      write(fp->fileno,fp->buffer,fp->size);
      fp->size=0;
    }
  }
  else 
  {
    // 
  }

}

void fclose_(FILE_* fp)
{
  fflush_(fp);
  close(fp->fileno);
}



void fflush_(FILE_* fp)
{
  if(fp->size>0) write(fp->fileno,fp->buffer,fp->size);
  fsync(fp->fileno); //强制要求OS进行外设刷新
  fp->size=0;
}




